package com.fishleap.controller;

import com.aliyun.oss.model.OSSObjectSummary;
import com.fishleap.bean.UpLoadResult;
import com.fishleap.service.FileUpLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/oss")
public class UploadController {

    @Autowired
    private FileUpLoadService fileUpLoadService;

    /**
     * 文件上传
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public UpLoadResult upload(@RequestParam("file") MultipartFile  multipartFile){
        return  fileUpLoadService.upload(multipartFile);
    }

    /**
     *  根据文件名进行下载
     * @param objectName
     * @param response
     * @throws IOException
     */
    @RequestMapping("/download")
    public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        //通知浏览器以附件形式下载
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
        fileUpLoadService.exportOssFile(response.getOutputStream(),objectName);
    }

    /**
     * 根据文件名删除
     * @param filePath
     * @return
     */
    @PostMapping("/delete")
    public UpLoadResult delete(@RequestParam("fileName") String filePath){
        return  fileUpLoadService.deleteFile(filePath);
    }

    /**
     *  查看桶内所有文件
     * @return
     * @throws Exception
     */
    @GetMapping("/list")
    public List<OSSObjectSummary> list() throws Exception {
        return fileUpLoadService.list();
    }

}
